
//
//  JCLStatusListViewModel.swift
//  WeiBo
//
//  Created by DDC on 2017/9/11.
//  Copyright © 2017年 DDC. All rights reserved.
//

import Foundation
import SDWebImage
/// 最大的刷新容错次数
private let maxErrroRefreshCount = 3

class JCLStatusListViewModel {
    /// 刷新空白内容的次数
    private var refreshErrorTimes = 0
    /// 数据模型数组
    lazy var statusList = [JCLStatusViewModel]()
    
    func loadStatus(pullUp:Bool, completion:@escaping (_ isSuccsee:Bool, _ shouldRefresh: Bool)->()) {
        
        if pullUp && refreshErrorTimes > maxErrroRefreshCount {
            completion(true, false)
            
            return
        }
        
        //获取下拉刷新最新的id
        let since_id = pullUp ? 0 : (self.statusList.first?.status.id ?? 0)
        let max_id = !pullUp ? 0 : (self.statusList.last?.status.id ?? 0)
        // 更改从数据库加载数据
        JCLStatusDAL.loadStatus(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
//        }
//        // 从网络加载数据
//        JCLNetWorkTools.shared.statusList(since_id: since_id , max_id: max_id) { (list, isSuccess) in
            
            //字典转模型
//            guard let array = NSArray.yy_modelArray(with: JCLStatus.self, json: list ?? []) as? [JCLStatus] else {
//                completion(true, false)
//                return
//            }
            // 网络请求失败
            if !isSuccess {
                completion(false, false)
                return
            }
            // 可变数组
            var array = [JCLStatusViewModel]()
            // 循环遍历
            for dict in list ?? [] {
                
                guard let model = JCLStatus.yy_model(with: dict) else {
                    //继续下一个循环
                    continue
                }
                // 添加到数组
                array.append(JCLStatusViewModel(model: model))
                
            }
            

            //上拉刷新
            if pullUp {
                self.statusList += array
            } else {
                
                //下拉刷新 拼接数据
                self.statusList = array + self.statusList
            }
            //没有刷新到数据
            if pullUp && array.count == 0 {
                
                self.refreshErrorTimes += 1
                
                completion(true,false)
            } else {
                //刷新数据成功
                self.cacheSingleImage(list: array, finished: completion)
//                //完成回调
//                completion(true,true)
               
            }
            
        }
    }
    
    /// 缓存单张图片
    ///
    /// - Parameter list: 根据返回的数组来遍历是否是单张图片
    ///   因为多张的图片可以按照九宫格布局来排布
    fileprivate func cacheSingleImage (list:[JCLStatusViewModel],finished:@escaping (_ isSuccsee:Bool, _ shouldRefresh: Bool)->()) {
        
        /// 缓存文件的大小
        var length = 0
        /// 队列组
        let group = DispatchGroup()
        for vm in list {
            // 判断是否是单张图片
            if vm.picURLs?.count != 1 {
                continue
            }
            // 运行到此 必须是单张图片了
            guard let picString = vm.picURLs?[0].thumbnail_pic,
                let picUrl = URL(string: picString) else {
                    continue
            }
            
            
            /// 进组
            group.enter()
            SDWebImageManager.shared().loadImage(with: picUrl, options: [], progress: nil, completed: { (image, _, _ , _, _, _) in
                /// 将image图片转换成二进制
                if let image = image ,
                   let data = UIImagePNGRepresentation(image) {
                    length += data.count
                }
                
                /// 出组 放在回调的最后一行
                /// 图像缓存成功,更新图像尺寸大小
                vm.updateSingleImageSize(image: image!)
                group.leave()
            })
            
        }
        /// 通知组 完成
        group.notify(queue: DispatchQueue.main) {
         
            print("图片缓存完成\(length/1024)")
            finished(true, true)
        }
        
    }
    
    
    
}
